package dyyx;

import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


public abstract class CommUtil {

	private static final int BUF_SIZE = 512;
	
	public static final String UTF8 = "utf8";
	
	
	public static int getInt(String str){
		try{
			return Integer.parseInt(str);
		}catch(Throwable e){
			return 0;
		}
	}


	public static void close(Closeable obj) {
		if (obj == null) {
			return;
		}
		try {
			obj.close();
		} catch (Throwable e) {

		}
	}

	public static String readString(String file, String charset) throws Exception {
		return readString(new File(file),charset);
	}

	
	public static byte[] readBytes(String file) throws Exception {
		return readBytes(new File(file));
	}
	
	public static String readString(File file, String charset) throws Exception {
		byte[] bytes = readBytes(file);
		if (bytes == null || bytes.length <= 0) {
			return null;
		}
		if (charset == null) {
			charset = UTF8;
		}
		return new String(bytes, charset);
	}

	
	public static byte[] readBytes(File file) throws Exception {
		InputStream is = null;
		try {
			is = new FileInputStream(file);
			return toBytes(is);
		} finally {
			close(is);
		}
	}
	
	
	public static void write(String file,byte[]bytes) throws Exception {
		OutputStream os = null;
		try {
			os = new FileOutputStream(new File(file));
			os.write(bytes);
		} finally {
			close(os);
		}
	}
	

	
	
	public static String readStringFromClassPath(String file, String charset) throws Exception {
		byte[] bytes = readBytesFromClassPath(file);
		if (bytes == null || bytes.length <= 0) {
			return null;
		}
		if (charset == null) {
			charset = UTF8;
		}
		return new String(bytes, charset);
	}
	
	public static String readStringFromClassPath(String file) throws Exception {
		return readStringFromClassPath(file,null);
	}


	
	public static byte[] readBytesFromClassPath(String file) throws Exception {
		InputStream is = null;
		try {
			// msg.txt
			is = CommUtil.class.getClassLoader().getResourceAsStream(file);
			
			return toBytes(is);
		} finally {
			close(is);
		}
	}
	

	private static byte[] toBytes(InputStream is) throws Exception {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		byte[] buf = new byte[BUF_SIZE];
		int len = 0;
		while ((len = is.read(buf)) != -1) {
			if (len > 0) {
				bos.write(buf, 0, len);
			}
		}
		return bos.toByteArray();
	}
	
	
	/**
	 * 判断文件是否为链接
	 * @param file
	 * @return
	 * @throws IOException
	 */
	public static boolean isSymlink(File file) throws IOException {
		if (file == null){
			return false;
		}		
		File canon;
		if (file.getParent() == null) {
			canon = file;
		} else {
			File canonDir = file.getParentFile().getCanonicalFile();
			canon = new File(canonDir, file.getName());
		}
		return !canon.getCanonicalFile().equals(canon.getAbsoluteFile());
	}



}
